from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .models import Genre, Movie, Rating, Comment


@admin.register(Genre)
class GenreAdmin(admin.ModelAdmin):
    """电影类型管理"""
    list_display = ('name',)
    search_fields = ('name',)


@admin.register(Movie)
class MovieAdmin(admin.ModelAdmin):
    """电影管理"""
    list_display = ('movie_id', 'title', 'year', 'get_genres')
    list_filter = ('year', 'genres')
    search_fields = ('title', 'movie_id')
    filter_horizontal = ('genres',)
    
    def get_genres(self, obj):
        return ", ".join([genre.name for genre in obj.genres.all()])
    get_genres.short_description = '类型'


@admin.register(Rating)
class RatingAdmin(admin.ModelAdmin):
    """评分管理"""
    list_display = ('user', 'movie', 'rating', 'timestamp')
    list_filter = ('rating', 'timestamp')
    search_fields = ('user__username', 'movie__title')
    readonly_fields = ('timestamp',)


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    """留言管理"""
    list_display = ('user', 'movie', 'content_preview', 'timestamp')
    list_filter = ('timestamp', 'movie__genres')
    search_fields = ('user__username', 'movie__title', 'content')
    readonly_fields = ('timestamp',)
    list_per_page = 20
    
    def content_preview(self, obj):
        return obj.content[:50] + '...' if len(obj.content) > 50 else obj.content
    content_preview.short_description = '留言内容'


# 自定义用户管理
class CustomUserAdmin(UserAdmin):
    """用户管理"""
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'is_active', 'date_joined')
    list_filter = ('is_staff', 'is_superuser', 'is_active', 'date_joined')
    search_fields = ('username', 'email', 'first_name', 'last_name')
    ordering = ('-date_joined',)
    
    # 添加统计信息
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.select_related()


# 重新注册User模型
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
